<template>
  <div class=""></div>
  <h2>计算属性和监视</h2>
  <fieldset>
    <legend>姓名操作</legend>
    姓：<input type="text" v-model="user.firstName"><br/>
    名：<input type="text" v-model="user.lastName">
  </fieldset>
  <fieldset>
    <legend>演示</legend>
    姓名：<input type="text" v-model="fullName1"><br/>
    姓名：<input type="text" v-model="fullName2"><br/>
    姓名：<input type="text" v-model="fullName3">
  </fieldset>
</template>
<script lang="ts">
import { computed, defineComponent, reactive, ref, watch, watchEffect } from 'vue'
export default defineComponent({
  name: 'App',
  setup () {
    const user = reactive({
      firstName: '东方',
      lastName: '不败'
    })
    // 计算属性
    const fullName1 = computed(() => {
      return user.firstName + '_' + user.lastName
    })

    const fullName2 = computed({
      get () {
        return user.firstName + '_' + user.lastName
      },
      set (val:string) {
        const names = val.split('_')
        user.firstName = names[0]
        user.lastName = names[1]
        // return val
      }
    })
    // 监视
    const fullName3 = ref('')
    watch(user, ({ firstName, lastName }) => {
      fullName3.value = firstName + '_' + lastName
    }, {
      immediate: true, // 默认会执行一次
      deep: true // 深度
    })

    // watchEffect(() => {
    //   fullName3.value = user.firstName + '_' + user.lastName
    // })

    watchEffect(() => {
      const names = fullName3.value.split('_')
      user.firstName = names[0]
      user.lastName = names[1]
    })

    watch([() => user.firstName, () => user.lastName, fullName3], () => {
      console.log('======')
    })

    return {
      user,
      fullName1,
      fullName2,
      fullName3
    }
  }
})
</script>
